package com.dsl.dslallinone.core;

import com.dsl.dslallinone.common.exception.DslException;
import com.dsl.dslallinone.dto.DslQuery;
import com.dsl.dslallinone.common.config.FilterConfig;
import com.dsl.dslallinone.dto.Granularity;
import org.springframework.stereotype.Component;

/**
 * 事实表解析器
 * 根据energy_type + granularity路由到对应的事实表
 */
@Component
public class FactTableResolver {

    /**
     * 解析表名
     */
    public String resolveTable(DslQuery query) {
        String energyType = extractEnergyType(query);
        Granularity granularity = query.getTime().getGranularity();

        return buildTableName(energyType, granularity);
    }

    /**
     * 从过滤条件中提取能源类型
     */
    private String extractEnergyType(DslQuery query) {
        if (query.getFilter() != null) {
            for (FilterConfig filter : query.getFilter()) {
                if ("energy_type".equals(filter.getField())) {
                    return String.valueOf(filter.getValue());
                }
            }
        }

        // 默认返回水表数据
        return "water";
    }

    /**
     * 构建表名
     */
    private String buildTableName(String energyType, Granularity granularity) {
        String tablePrefix;
        
        // 根据能源类型确定表前缀
        switch (energyType.toLowerCase()) {
            case "water":
                tablePrefix = "water";
                break;
            case "electric":
                tablePrefix = "electric";
                break;
            case "gas":
                tablePrefix = "gas";
                break;
            case "heat":
                tablePrefix = "heat";
                break;
            default:
                throw new DslException("不支持的能源类型: " + energyType);
        }

        // 根据时间粒度确定表后缀
        String tableSuffix;
        switch (granularity) {
            case HOUR:
                tableSuffix = "hour_fact";
                break;
            case DAY:
                tableSuffix = "day_fact";
                break;
            case MONTH:
                tableSuffix = "month_fact";
                break;
            default:
                throw new DslException("不支持的时间粒度: " + granularity);
        }

        return tablePrefix + "_" + tableSuffix;
    }

    /**
     * 获取支持的表列表
     */
    public String[] getSupportedTables() {
        return new String[]{
            "water_hour_fact", "water_day_fact", "water_month_fact",
            "electric_hour_fact", "electric_day_fact", "electric_month_fact",
            "gas_hour_fact", "gas_day_fact", "gas_month_fact",
            "heat_hour_fact", "heat_day_fact", "heat_month_fact"
        };
    }
}
